import { Injectable } from "@nestjs/common";
import { Repository } from "typeorm";
import { InjectRepository } from "@nestjs/typeorm";
import { CacheRedisService } from "src/cache-redis/cache-redis.service";
import { loginData, registerData, forgetData } from "src/dto/user.dto";
import { User } from "src/entity/user.entity";
import { Room } from "src/entity/room.entity";
import { error, getTimeStamp, success, getAuth } from "src/utils/common";
import * as fs from "fs";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userEntity: Repository<User>,
    @InjectRepository(Room)
    private roomEntity: Repository<Room>,
    private redis: CacheRedisService
  ) {}

  /**
   *
   * @param loginData 前端传输过来的账号密码
   * @returns 返回token值
   */
  async loginPassword(loginData: loginData) {
    const res = await this.userEntity.findOne({
      where: {
        user_name: loginData.user_name,
        user_password: loginData.user_password,
      },
    });
    if (res) {
      const auth = await this.createAuth(res);
      return success("ok", { token: auth });
    }
    return error("账号或者密码错误");
  }

  /**
   *
   * @param loginData 前端传输过来的账号密码
   * @returns 返回token值
   */
  async loginEmail(loginData: loginData) {
    //查询是否有值code
    const res = await this.redis.get(loginData.user_name);
    this.redis.del(loginData.user_name);
    if (res == loginData.user_password) {
      const data = await this.userEntity.findOne({
        where: { user_name: res.user_name },
      });
      const auth = await this.createAuth(data);
      return success("ok", { token: auth });
    }
    return error("账号或者密码错误");
  }

  async register(registerData: registerData) {
    const { user_name, user_password } = registerData;
    const ifReg = await this.userEntity.findOne({ where: { user_name } });
    if (ifReg) {
      return error("邮箱已经存在");
    } else {
      const data = this.userEntity.create({
        user_name,
        user_nickname: "",
        user_password,
        user_creationTime: getTimeStamp(),
      });
      await this.userEntity.save(data);
      return success("注册成功");
    }
  }

  async getMyInfo(user: User) {
    return await this.roomEntity.findOne({
      where: { create_id: user.user_id },
    });
  }

  async forget(forget: forgetData, token: string) {
    const code = await this.redis.get(forget.user_name);
    if (code == forget.code) {
      //删除token
      await this.redis.del(token);
      await this.redis.del(forget.user_name);
      //更新数据
      await this.userEntity.update(
        { user_name: forget.user_name },
        { user_password: forget.user_password }
      );
      return true;
    }
    return false;
  }

  async updateInfo(user: User, type, token: string) {
    //更新数据库
    await this.userEntity.update({ user_id: user.user_id }, user);
    if (type) {
      this.redis.del(token);
    } else {
      this.redis.set(token, user, 2592000);
    }
  }
  async uploadHead(buffer: Buffer, filename: string, token: string) {
    const path = `/public/head/${filename}`;
    try {
      const userData = await this.redis.get(token);
      const updateState = await this.userEntity.update(
        { user_id: userData.user_id },
        { user_image: path }
      );
      fs.writeFileSync("." + path, buffer);
      if (updateState.affected) {
        userData.user_image = path;
        //更新redis缓存
        await this.redis.set(token, userData, 2592000);
        return path;
      }
      return "";
    } catch (error) {
      return "";
    }
  }
  /**
   *
   * @param data 需要放到redis中的数据
   * @returns  返回生成的令牌
   */
  async createAuth(data: any): Promise<string> {
    const auth = getAuth();
    //设置生存时间为30天
    await this.redis.set(auth, data, 2592000);
    return auth;
  }
}
